import datasetService from '@/api/services/datasetService';
import knowService from '@/api/services/knowService';
import { FaqCollection, FaqDataset } from '@/types/know/know';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Input, message, Modal, Tooltip } from 'antd';
import { memo, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

interface Props {
  onDatasetChange: (dataset: FaqDataset) => void;
}

const DatasetList = ({ onDatasetChange }: Props) => {
  const [selectedDataset, setSelectedDataset] = useState<FaqDataset | null>(null);
  const [selectedCollection, setSelectedCollection] = useState<FaqCollection | null>(null);
  const [datas, setDatas] = useState<FaqDataset[]>([]);
  const [open, setOpen] = useState(false);
  const [datasetName, setDatasetName] = useState('');

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || "";

  const getDatas = async () => {
    try {
      const res = await knowService.getFaqDataset({ page: 1, page_size: 100, app_id: appId });
      setDatas(res.list);
      if (res.list.length > 0) {
        const dataset = res.list[0];
        setSelectedDataset(dataset);
        setSelectedCollection(dataset.children[0]);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const handleSelectDataset = (dataset: FaqDataset) => {
    setSelectedDataset(dataset);
  };

  const handleCreateDataset = async () => {
    if (!datasetName.trim()) {
      message.warning('请输入知识库名称');
      return;
    }

    if (datas.some((item) => item.datasetName === datasetName)) {
      message.warning('知识库名称已存在');
      return;
    }

    try {
      const res = await datasetService.createFaqDataset(datasetName, appId);
      if (res) {
        getDatas();
        reset();
      }
      setDatasetName('');
    } catch (error) {
      console.error(error);
    }
  };

  const reset = () => {
    setOpen(false);
    setDatasetName('');
  };

  useEffect(() => {
    if (selectedDataset && selectedDataset?.children.length > 0) {
      setSelectedCollection(selectedDataset.children[0]);
    }
    onDatasetChange(selectedDataset!);
  }, [selectedDataset]);

  useEffect(() => {
    getDatas();
  }, []);

  return (
    <div className="flex h-full flex-1 rounded-lg border-2 border-WhiteSmoke">
      <div className="w-1/4 p-4">
        <div className="mb-4 flex items-center text-base text-[#474C5F]">
          知识库{' '}
          <Tooltip title="新建知识库">
            <Button
              icon={<PlusOutlined />}
              type="text"
              className="ml-auto"
              onClick={() => setOpen(true)}
            />
          </Tooltip>
        </div>
        <div className="flex flex-col gap-2">
          {datas.map((item) => {
            return (
              <div
                key={item.datasetId}
                className="cursor-pointer"
                onClick={() => {
                  handleSelectDataset(item);
                }}
              >
                <div
                  className={`${selectedDataset?.datasetId === item.datasetId
                    ? 'text-[#6640FF]'
                    : 'text-[#A5A9BB]'
                    } truncate text-nowrap text-sm`}
                >
                  {item.datasetName}
                </div>
              </div>
            );
          })}
        </div>
      </div>
      <div className="h-full border-2 border-WhiteSmoke"></div>
      <div className="flex h-full flex-1 flex-col overflow-y-hidden p-4">
        <div className="mb-4 h-8 text-base text-[#474C5F]">选择数据集进行存储</div>
        <div className="flex flex-wrap items-start gap-2 overflow-y-auto p-2">
          {selectedDataset?.children?.map((item) => {
            return (
              <div
                key={item.collectionId}
                onClick={() => {
                  setSelectedCollection(item);
                }}
                className={`${selectedCollection?.collectionId === item.collectionId
                  ? 'border-gray-700 bg-[#F4F5F8]'
                  : ''
                  } h-10 cursor-pointer truncate text-nowrap rounded-lg border-2 border-WhiteSmoke p-2 text-sm hover:border-DarkGrey hover:bg-[#F4F5F8] active:scale-105`}
              >
                <span>{item.collectionName}</span>
              </div>
            );
          })}
        </div>
      </div>
      <Modal open={open} onCancel={reset} footer={null}>
        <div className="m-2 text-center text-lg font-bold">新建知识库</div>
        <div className="m-4 text-center">
          <Input
            value={datasetName}
            onChange={(e) => setDatasetName(e.target.value)}
            placeholder="请输入知识库名称"
          />
        </div>
        <div className="m-4 flex justify-center gap-4">
          <Button onClick={reset}>取消</Button>
          <Button type="primary" onClick={handleCreateDataset}>
            确认
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default memo(DatasetList);
